﻿using ConsoleApp.Model.Dto;
using ConsoleApp.Model.Entity;
using ConsoleApp.Service;
using Newtonsoft.Json;
using Quartz;

namespace ConsoleApp.DispatchTask
{
    [PersistJobDataAfterExecution]
    [DisallowConcurrentExecution]
    public class SendMessageJob : IJob
    {

        
        private readonly ILogger<SendMessageJob> _logger;
        private readonly IServiceProvider _serviceProvider;
        //private readonly IHttpService _httpService;
        
        
        public SendMessageJob(ILogger<SendMessageJob> logger, IServiceProvider serviceProvider/*, IHttpService httpService*/)
        {
            _logger = logger;
            _serviceProvider = serviceProvider;
            //_httpService = httpService;

            Console.WriteLine("111");
        }

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                await Task.Run(() =>
                {
                    Console.WriteLine();
                    Console.WriteLine("################################################");
                    Console.WriteLine($"now start test {DateTime.Now}");
                    _logger.LogInformation ($"{DateTime.Now.ToString()}：now start test");
                    DoSign();
                    Console.WriteLine("################################################");
                    Console.WriteLine();
                });
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
        }
        
        public async void DoSign()
    {
        try
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var _ctx = scope.ServiceProvider.GetRequiredService<AutoDingContext>();
                var _httpService = scope.ServiceProvider.GetRequiredService<IHttpService>();
                
                // do something with context

                TimeSpan mTimeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0);
                long timestamp = (long)mTimeSpan.TotalSeconds * 1000;

                string dbUser = _ctx.Configs.Where(x => x.ConfigKey == "LOGIN_USER").FirstOrDefault().ConfigValue;
                string dbPassword = _ctx.Configs.Where(x => x.ConfigKey == "LOGIN_PWD").FirstOrDefault().ConfigValue;

                string username = DoEncrypt.getEnpcrypt(dbUser);
                string password = DoEncrypt.getEnpcrypt(dbPassword);
                string t = DoEncrypt.getEnpcrypt(timestamp.ToString());

                LoginModel loginParam = new LoginModel()
                {
                    phone = username,
                    password = password,
                    t = t
                };

                var infoRes = await _httpService.GetOrSaveTokenInfo(loginParam);

                double baseLog = 109.53496767736814; // 经度基准点  
                double baseLat = 24.401668705191504; // 维度基准点  
                double radius = 200; // 距离基准点的半径  

                string loga, lata;

                HelpFunc.GenerateRandomGps(baseLog, baseLat, radius, out loga, out lata);

                string description = "";
                string province = "";

                string city = "";
                string longitude = loga;
                string latitude = lata;
                string address = "广西壮族自治区 · 柳州市 · 鱼峰区 · 在柳州职业技术学院(官塘校区)附近";

                SignRes res1 = await _httpService.tosign(description, address, province, city, longitude, latitude, t,
                    infoRes.token, infoRes.planId, infoRes.userId);

                Log log = new Log();
                if (res1.code == 200)
                {
                    log.Msg = "打卡成功";
                    log.CreateTime = DateTime.Now;
                }
                else
                {
                    string err = JsonConvert.SerializeObject(res1);
                    log.Msg = $"打卡失败,接口响应为:{err}";
                    log.CreateTime = DateTime.Now;
                }

                Console.WriteLine($"{log.Msg}");
                _ctx.Logs.Add(log);
                await _ctx.SaveChangesAsync();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }


        
    }
}